package com.example.cpoopc.listview_test;

import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;


public class MainActivity extends ActionBarActivity {
    MyListView lvContent;
    VerticalScrollview rl;
    ImageView ivHeader;
    RelativeLayout rlContainer;
    int mHeadHeight;
    MyAdapter myAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        strList = new ArrayList<String>();
        for (int i=0;i<20;i++){
            strList.add(String.valueOf(i));
        }
        rl = (VerticalScrollview) findViewById(R.id.root);
        lvContent = (MyListView) findViewById(R.id.lv_content);
        rl.lv = lvContent;
//        setListViewHeightBasedOnChildren(lvContent);
        myAdapter = new MyAdapter();
        lvContent.setAdapter(myAdapter);
        lvContent.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Toast.makeText(MainActivity.this, "position:"+position, 0).show();
			}
        	
		});
        lvContent.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            	if(firstVisibleItem == 0){
            		if(lvContent.getScrollY() == 0 && lvContent.getChildAt(0)!=null){
//            			moveChild = false;
            			if(lvContent.getChildAt(0).getTop()==0){
            			moveChild = false;
            				
            			}
            			lvContent.getChildAt(0).getTop();
            			Log.d("cp:lv", "lvContent.getChildAt(0).getTop():"+lvContent.getChildAt(0).getTop());
            		}
            	}
            	
            	Log.d("-----cp:","firstVisibleItem:"+firstVisibleItem+" visibleItemCount:"+visibleItemCount+" totalItemCount:"+totalItemCount);
            	if(firstVisibleItem + visibleItemCount >= totalItemCount){
                    ArrayList<String> strings = new ArrayList<String>();
                    Log.d("-----cp:","add");
                    for (int i=0;i<10;i++){
                        strings.add(String.valueOf(totalItemCount + i));
                    }
                    strList.addAll(strings);
                    myAdapter.notifyDataSetChanged();
                }
            }
        });
        ivHeader = (ImageView) findViewById(R.id.iv_header);
        rlContainer = (RelativeLayout) findViewById(R.id.rl_container);
        rl.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

            @Override
            public void onGlobalLayout() {
                // Ensure you call it only once :
                rl.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                int height = getWindowManager().getDefaultDisplay().getHeight() - getSupportActionBar().getHeight();
                mHeadHeight = ivHeader.getHeight();
//                height -= mHeadHeight;
                rlContainer.getLayoutParams().height = height;
                rl.invalidate();
                // Here you can get the size :)
            }
        });

        lvContent.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
//                int[] location = new int[2];
//                lvContent.getLocationInWindow(location);
//                if(location[1]==112){
//                    rl.setScrollEnable(true);
//                }
                int firstVisibleposition = lvContent.getFirstVisiblePosition();
//                if(firstVisibleposition == 0 && lvContent.getChildAt(0).getTop()==0){
//                    Log.d("cp:","firstVisibleposition == 0 && lvContent.getChildAt(0).getTop()==0");
//                    return true;
//                }
                if(lvContent.getScrollY() != 0){

                }
//                v.getParent().requestDisallowInterceptTouchEvent(moveChild);
                return false;
            }
        });
//        lvContent.
//        rl.scrollTo(0,300);
    }

    private ArrayList<String> strList = new ArrayList<String>();

    class MyAdapter extends BaseAdapter{

        @Override
        public int getCount() {
            return strList.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            String tag = convertView==null?"converview==null":"不空";
            if(convertView == null){
                convertView = LayoutInflater.from(MainActivity.this).inflate(R.layout.item_listview,null);
                Log.d("cp:",position+"converview==null");
            }
            TextView tv = (TextView) convertView.findViewById(R.id.tv);
            tv.setText(tag+"position:"+position);
            return convertView;
        }
    }


    /**** Method for Setting the Height of the ListView dynamically.
     **** Hack to fix the issue of not showing all the items of the ListView
     **** when placed inside a ScrollView  ****/
//    public static void setListViewHeightBasedOnChildren(ListView listView) {
//        ListAdapter listAdapter = listView.getAdapter();
//        if (listAdapter == null)
//            return;
//
//        int desiredWidth = View.MeasureSpec.makeMeasureSpec(listView.getWidth(), View.MeasureSpec.UNSPECIFIED);
//        int totalHeight = 0;
//        View view = null;
//        for (int i = 0; i < listAdapter.getCount(); i++) {
//            view = listAdapter.getView(i, view, listView);
//            if (i == 0)
//                view.setLayoutParams(new ViewGroup.LayoutParams(desiredWidth, ViewGroup.LayoutParams.WRAP_CONTENT));
//
//            view.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
//            totalHeight += view.getMeasuredHeight();
//        }
//        ViewGroup.LayoutParams params = listView.getLayoutParams();
//        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
//        listView.setLayoutParams(params);
//        listView.requestLayout();
//    }

    int headHeight;
    boolean inTop = false;
    float posX,posY;
    boolean moveChild;
    
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
    	// TODO Auto-generated method stub
    	if(headHeight==0){
			int[] locationHead = new int[2];
			rl.getLocationInWindow(locationHead);
			headHeight = locationHead[1];
			Log.d("cp:headHeight", ".headHeight:"+headHeight);
    	}
    	lvContent.getTop();
    	int[] location = new int[2];
    	lvContent.getLocationInWindow(location);
		Log.d("cp:lv", "lv.top:"+location[1]);
		if(location[1]<=headHeight){
			inTop = true;
		}else{
			inTop = false;
		}
    	switch (ev.getAction()) {
		case MotionEvent.ACTION_DOWN:
			posX = ev.getX();
			posY = ev.getY();
			break;
		case MotionEvent.ACTION_MOVE:
			if(inTop && ev.getY()-posY<0){
				moveChild = true;
				lvContent.moveChild = true;
			}else if(!inTop && ev.getY()-posY>0){
				moveChild = false;
				lvContent.moveChild = false;
			}
			
			break;
		default:
			break;
		}
    	rl.giveChild = moveChild; 
    	if(moveChild){
    		Log.d("cp:lv", "lvContent.dispatchTouchEvent:"+location[1]);
    		lvContent.dispatchTouchEvent(ev);
    	}
    	return super.dispatchTouchEvent(ev);
    }
    
    
}
